﻿define(['jquery', 'swfupload', 'standardArtDialog'], function ($, SWFupload, standardArtDialog) {
    var normalDialog = function (msg, fn) {
        standardArtDialog.dialog({
            drag: true,
            lock: true,
            width: 310,
            height: 50,
            title: '提示',
            content: msg,
            ok: function () {
                if (fn) {
                    fn();
                } else {
                    this.close();
                }
            }
        });
    };
    var getLength = function (value) {
        var replaceVal = value.replace(/[^\u0000-\u00ff]/g, "11");
        return replaceVal.length;
    };
    var valid = function (data) {
        if (data.name.length == 0) {
            $(".c_msg").html("名称不能为空");
            return false;
        } else if (getLength(data.name) > 50) {
            $(".c_msg").html('名称长度应不大于50个字符，一个汉字等于两个字符');
            return false;
        }
        if (data.position < 0) {
            $(".c_msg").html("请选择位置");
            return false;
        }
        if (data.url.length == 0) {
            $(".c_msg").html("超链接无效");
            return false;
        }
        if (data.image == '') {
            $(".c_msg").html('请上传图片');
            return false;
        }
        return true;
    }

    // 文件选择框关闭时触发
    var fileDialogComplete = function (selected, queued) {
        if (selected > 1) {
            normalDialog('最多只能上传1张图片');
            return;
        }
        this.startUpload();
    };
    // 文件上传成功后触发
    var uploadSuccess = function (file, serverData) {
        var result = jQuery.parseJSON(serverData);
        if (!result)
            normalDialog("未能上传成功，请刷新重试！");
        if (result.IsSuccess) {
            var fileKey = result.Value;
            $("#imageKey").val(fileKey);
            $("#image").attr("src", fileKey);
        } else {
            normalDialog('上传图片出错' + result.Message);
        }
        $("#imageUploadProgress").empty();
    };
    var uploadError = function (obj, code, msg) {
        normalDialog("swf error code: " + code + "\r\nhttp status: " + msg
                + "\r\n请重试！");
        $("#imageUploadProgress").html("");
    };
    var uploadProgress = function (obj, completeBytes, totalBytes) {
        $("#imageUploadProgress").html(
                "正在上传..." + ((completeBytes / totalBytes).toFixed(2) * 100)
                        + "%");
    };
    // 初始化单上传控件
    var initSwfUpload = function () {
        var fileUploadSettings = {
            upload_url: '/upload',
            file_types: '*.jpeg;*.jpg;*.png;*.gif;*.bmp',
            file_types_description: '图片类型',
            button_placeholder_id: 'placeholder',
            file_upload_limit: 0,
            prevent_swf_caching: false,
            button_width: 78,
            button_height: 20,
            button_cursor: SWFUpload.CURSOR.HAND,
            button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
            button_text: '本地上传',
            button_text_left_padding: 10,
            button_text_top_padding: 2,
            file_post_name: "fileData",
            file_dialog_complete_handler: fileDialogComplete,
            upload_success_handler: uploadSuccess,
            upload_progress_handler: uploadProgress,
            // upload_complete_handler: uploadComplete,
            upload_error_handler: uploadError,
            flash_url: '/Content/Scripts/Components/swfupload/swfupload.swf',
            debug: false
        };
        var fileUpload = new SWFUpload(fileUploadSettings);
    };

    var init = function () {
        initSwfUpload();
        var resetPanel = function () {
            $("#name").val("");
            $("#position").val("");
            $("#url").val("");
            $("#imageKey").val("");
        }
        $("a[name='deleteLink']").on("click", function () {
            var e = this;
            standardArtDialog.dialog({
                lock: true,
                title: '提示',
                content: '确定要删除该条记录么？',
                button: [
                    {
                        value: '确定',
                        callback: function () {
                            var id = $(e).parent().find("input[type='hidden']").val();
                            $.ajax({
                                type: 'post',
                                url: '/recommend/delete',
                                data: { id: id },
                                success: function (data) {
                                    if (data.IsSuccess && data.Value > 0) {
                                        standardArtDialog.dialog({
                                            lock: true,
                                            title: '提示',
                                            content: '删除成功',
                                            ok: function () { location.reload(); }
                                        });
                                    } else {
                                        normalDialog("删除失败" + data.Message);
                                    }
                                }
                            });
                        }
                    },
                    {
                        value: '取消',
                        focus: true,
                        callback: function () {
                            this.close();
                        }
                    }
                ]
            });
        });
        $("#btnAdd").on("click", function () {
            resetPanel();
            standardArtDialog.dialog({
                drag: true,
                lock: true,
                width: 310,
                height: 50,
                title: '添加推荐',
                content: document.getElementById("addPanel"),
                button: [
                    {
                        value: '确定',
                        callback: function () {
                            var data = {
                                name: $("#name").val(),
                                position: $("#position").val(),
                                url: $("#url").val(),
                                image: $("#imageKey").val()
                            }
                            if (valid(data)) {
                                $.ajax({
                                    type: "post",
                                    data: data,
                                    url: "/Recommend/Add",
                                    success: function (res) {
                                        if (res.IsSuccess) {
                                            normalDialog('添加成功', function () {
                                                this.close();
                                                location.reload();
                                            });
                                        }
                                    }
                                });
                            }
                            return false;
                        }
                    },
                    {
                        value: '取消',
                        callback: function () {
                            this.close();
                        }
                    }
                ]
            });
        });
    }
    return {
        init: init
    };
});